package com.ytf.test.fifth;

/**
 * @author: YTF
 * @date: 2024/9/20 11:43
 * @version: 1.0
 * @description: 静态初始化
 */
public class StaticInitialization {
    public static void main(String[] args) {
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        table.f2(1);
        cupboard.f3(1);

        /**
         * Output:
         * Bowl(1)
         * Bowl(2)
         * Table()
         * f1(2)
         * Bowl(4)
         * Bowl(5)
         * Bowl(3)
         * Cupboard()
         * f1(2)
         * Creating new Cupboard() in main
         * Bowl(3)
         * Cupboard()
         * f1(2)
         * Creating new Cupboard() in main
         * Bowl(3)
         * Cupboard()
         * f1(2)
         * f2(1)
         * f3(1)
         *
         * 总结：
         *  对象在创建的时候才会初始化，初始化的顺序是先静态对象（静态对象在构造器之前）然后非静态对象。
         *  静态成员（包括静态变量和静态代码块）的初始化是在构造器执行之前完成的。这是因为静态成员属于类级别，而构造器属于实例级别。
         *  当一个类被加载时，JVM会首先执行静态成员的初始化，然后才允许创建类的实例并执行构造器。
         */
    }
    static Table table =new Table();
    static Cupboard cupboard = new Cupboard();
}

class Bowl {
    public Bowl(int marker) {
        System.out.println("Bowl(" + marker + ")");
    }

    void f1(int marker) {
        System.out.println("f1(" + marker + ")");
    }
}

class Table {
    static Bowl bowl1 = new Bowl(1);

    public Table() {
        System.out.println("Table()");
        bowl2.f1(2);
    }

    void f2(int marker) {
        System.out.println("f2(" + marker + ")");
    }

    static Bowl bowl2 = new Bowl(2);
}
class Cupboard{
    Bowl bowl3 = new Bowl(3);
    static Bowl bowl4 = new Bowl(4);

    public Cupboard() {
        System.out.println("Cupboard()");
        bowl4.f1(2);
    }

    void f3(int marker) {
        System.out.println("f3(" + marker + ")");
    }
    static Bowl bowl5 = new Bowl(5);

}
